import { defineStore } from 'pinia'
import { ref } from 'vue'
import fetchRouteTree from '@/api/routesTree'
import { router } from '@/router/index'

export const useRoutesStore = defineStore('routeStore', () => {
  const routesTree = ref([])

  const loadRouteTree = async () => {
    const tree = await fetchRouteTree()
    routesTree.value = tree
    console.log(tree);
  }

  const resolveRoutesTree = (routesTree, modules) => {
      routesTree.forEach(rt => {
        if (!rt.children) {
          if (rt.component) {
            const component = modules[`../views/${rt.component}`]
            rt.component = component
          }
        } else {
          return resolveRoutesTree(rt.children, modules)
        }
      })
  }

  const addRoutes = () => {
    console.log(routesTree.value);
    const modules = import.meta.glob('../views/*/*.vue')
      resolveRoutesTree(routesTree.value, modules)
      routesTree.value.forEach(rt => router.addRoute('layouts', rt))

  }

  return {
    routesTree,
    loadRouteTree,
    addRoutes
  }
})
